package com.guanyong.webapi.config;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.UUID;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.crypto.dsig.SignatureMethod;

import com.google.gson.Gson;
import org.apache.commons.codec.binary.Base64;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Created by Administrator on 2017/7/17 0017.
 */
@Service
public class VideoLocalUtil {

    @Value("${ali.video.accessKeyId}")
    String accessKeyId ;
    @Value("${ali.video.accessKeySecret}")
    String accessKeySecret ;

        public static void main(String[] args) throws Exception {
            VideoLocalUtil a = new VideoLocalUtil();
//		a.get();
            System.out.println("--------"+a.get("25f0c95fb7c1475c9a5c782ea751fa86"));

//            int start = result.indexOf("\"PlayURL\":")+11;
//            int end = result.indexOf("\",\"Width\":");
//            System.out.println(result.substring(start, end));
        }



        public  String  get(String videoId) throws Exception{
            final String HTTP_METHOD = "GET";
            Map<String, String> parameterMap = new HashMap<String, String>();
            // ¼ÓÈëÇëÇó¹«¹²²ÎÊý
            parameterMap.put("Action", "GetPlayInfo");
            parameterMap.put("VideoId", videoId);
            parameterMap.put("Version", "2017-03-21");
            parameterMap.put("AccessKeyId", accessKeyId); //´Ë´¦ÇëÌæ»»³ÉÄú×Ô¼ºµÄAccessKeyId
            parameterMap.put("Timestamp", VideoLocalUtil.formatIso8601Date(new Date()));//´Ë´¦½«Ê±¼ä´Á¹Ì¶¨Ö»ÊÇ²âÊÔÐèÒª£¬ÕâÑù´ËÊ¾ÀýÖÐÉú³ÉµÄÇ©ÃûÖµ¾Í²»»á±ä£¬·½±ãÄú¶Ô±ÈÑéÖ¤£¬¿É±äÊ±¼ä´ÁµÄÉú³ÉÐèÒªÓÃÏÂ±ßÕâ¾äÌæ»»
            //parameterMap.put("Timestamp", formatIso8601Date(new Date()));
            parameterMap.put("SignatureMethod", "HMAC-SHA1");
            parameterMap.put("SignatureVersion", "1.0");
//	    parameterMap.put("SignatureNonce", "578a50c1-280d-4a34-bffc-e06aa6b2df76");//´Ë´¦½«Î¨Ò»Ëæ»úÊý¹Ì¶¨Ö»ÊÇ²âÊÔÐèÒª£¬ÕâÑù´ËÊ¾ÀýÖÐÉú³ÉµÄÇ©ÃûÖµ¾Í²»»á±ä£¬·½±ãÄú¶Ô±ÈÑéÖ¤£¬¿É±äÎ¨Ò»Ëæ»úÊýµÄÉú³ÉÐèÒªÓÃÏÂ±ßÕâ¾äÌæ»»
            parameterMap.put("SignatureNonce", UUID.randomUUID().toString());
            parameterMap.put("Format", "JSON");
            // ¼ÓÈë·½·¨ÌØÓÐ²ÎÊý
//	    parameterMap.put("VideoId", "68a4d2629a339db3207963ac073a88cd");
            // ¶Ô²ÎÊý½øÐÐÅÅÐò
            List<String> sortedKeys = new ArrayList<String>(parameterMap.keySet());
            Collections.sort(sortedKeys);
            // Éú³ÉstringToSign×Ö·û
            final String SEPARATOR = "&";
            final String EQUAL = "=";
            StringBuilder stringToSign = new StringBuilder();
            stringToSign.append(HTTP_METHOD).append(SEPARATOR);
            stringToSign.append(percentEncode("/")).append(SEPARATOR);
            StringBuilder canonicalizedQueryString = new StringBuilder();
            for (String key : sortedKeys) {
                // ´Ë´¦ÐèÒª¶ÔkeyºÍvalue½øÐÐ±àÂë
                String value = parameterMap.get(key);
                canonicalizedQueryString.append(SEPARATOR).append(percentEncode(key)).append(EQUAL).append(percentEncode(value));
            }
            // ´Ë´¦ÐèÒª¶ÔcanonicalizedQueryString½øÐÐ±àÂë
            stringToSign.append(percentEncode(canonicalizedQueryString.toString().substring(1)));


            final String ALGORITHM = "HmacSHA1";
            final String secret = accessKeySecret;//´Ë´¦ÇëÌæ»»³ÉÄúµÄAccessKeySecret
            SecretKey key = new SecretKeySpec((secret + SEPARATOR).getBytes(ENCODE_TYPE), SignatureMethod.HMAC_SHA1);
            Mac mac = Mac.getInstance(ALGORITHM);
            mac.init(key);
            String signature = URLEncoder.encode(new String(new Base64().encode(mac.doFinal(stringToSign.toString().getBytes(ENCODE_TYPE))),
                    ENCODE_TYPE), ENCODE_TYPE);
            // Éú³ÉÇëÇóURL
            StringBuilder requestURL;
            requestURL = new StringBuilder("http://vod.cn-shanghai.aliyuncs.com?");
            requestURL.append(URLEncoder.encode("Signature", ENCODE_TYPE)).append("=").append(signature);
            for (Map.Entry<String, String> e : parameterMap.entrySet()) {
                requestURL.append("&").append(percentEncode(e.getKey())).append("=").append(percentEncode(e.getValue()));
            }
            System.out.println(requestURL.toString());

            String result = "";
            result =VideoLocalUtil.sendGet(requestURL.toString());
            System.out.println(result);
//            Gson gson = new Gson();
//            HashMap<String,Object> obj=  gson.fromJson(result,HashMap.class);
//            for (String key1 : obj.keySet()) {
//                System.out.println("key= "+ key1 + " and value= " + obj.get(key1));
//            }
//            HashMap<String,Object> obj1 =gson.fromJson(obj.get("PlayInfoList").toString(),HashMap.class);
//
//
//
//            System.out.print(obj.get("RequestId"));
            int temp = result.indexOf("{\"Format\":\"mp4\"");
            result = result.substring(temp, result.length());
            int start = result.indexOf("\"PlayURL\":")+11;
            int end = result.indexOf("\",\"Width\":");

//            JSONArray json = new JSONArray(requestURL.toString());
//            JSONObject resultJson = json.optJSONObject(0);
//            String username = resultJson.getString("PlayInfoList");
//            System.out.println(username);


            return result.substring(start, end);
        }


        private static final String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
        private static String formatIso8601Date(Date date) {
            SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT);
            df.setTimeZone(new SimpleTimeZone(0, "GMT"));
            return df.format(date);
        }

        private static final String ENCODE_TYPE = "UTF-8";
        private static String percentEncode(String value) throws UnsupportedEncodingException {
            if (value == null) return null;
            return URLEncoder.encode(value, ENCODE_TYPE).replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
        }



    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url ;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
            connection.setRequestProperty("Cache-Control", "max-age=0");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36");
            connection.setUseCaches(false);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return result;
    }




}
